package com.ysyc.driver_ee.base;


import android.app.Dialog;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.LayoutRes;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.animation.RotateAnimation;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.orhanobut.hawk.Hawk;
import com.ysyc.driver_ee.activity.MainActivity;
import com.ysyc.driver_ee.activity.OrderNavigationActivity;
import com.ysyc.driver_ee.api.HttpResource;
import com.ysyc.driver_ee.api.NetworkCallback;
import com.ysyc.driver_ee.api.RetrofitClient;
import com.ysyc.driver_ee.constant.HawkKeys;
import com.ysyc.driver_ee.manager.ActivityManagerHelp;
import com.ysyc.driver_ee.tools.AndroidBug5497Workaround;
import com.ysyc.driver_ee.tools.LocationHelp;
import com.ysyc.driver_ee.tools.StatusBarLightUtils;
import com.ysyc.driver_ee.tools.StringUtils;
import com.ysyc.driver_ee.widget.LoadingDialog;

import org.greenrobot.eventbus.EventBus;

import java.lang.reflect.Field;
import java.util.ArrayList;

import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.reactivex.Observable;
import io.reactivex.disposables.Disposable;

/**
 *
 */
public abstract class BaseActivity extends AppCompatActivity {
    private Unbinder unbinder;

    public ArrayList<BaseFragment> fragments = new ArrayList<>();
    /*    private SureAndCancelDialog dialog;*/
    public AMapLocationClient locationClient;
    public AMapLocation location;
    private Disposable timeSubscribe;
    /**
     * 加载的dialog
     */
    private LoadingDialog loadingDialog;
    private RotateAnimation rotateAnimation;
    private NetworkCallback<Object> objectNetworkCallback;
    private String address;
    private LocationHelp locationHelp;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        restoreSavedInstanceState(savedInstanceState);
        setStatusBarCol();
        setContentView(getLayoutId());
        AndroidBug5497Workaround.assistActivity(this);
        unbinder = ButterKnife.bind(this);
        ActivityManagerHelp.getInstance().add(this);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        initData(savedInstanceState);
        initView();
        mapMoveReport();
        StatusBarLightUtils.setStatusBarLightMode(this);
//        EventBus.getDefault().register(this);
    }

    protected void initData(Bundle savedInstanceState) {

    }

    private void mapMoveReport() {
        objectNetworkCallback = new NetworkCallback<>(new HttpResource<Object>() {
            @Override
            public void onSuccess(Object baseBean) {

            }

            @Override
            public void onFailure(String errorDes) {
            }

            @Override
            public void onLoading(Dialog dialog) {
            }
        });
        if(getClass().getName().equals(MainActivity.class.getName())||getClass().getName().equals(OrderNavigationActivity.class.getName())) {
        if (locationHelp == null) {
                locationHelp = new LocationHelp(this, (mLocationClient, aMapLocation) -> {
                    locationClient = mLocationClient;
                    location = aMapLocation;
                    address = aMapLocation.getAddress();
                    String province = aMapLocation.getProvince();
                    if (!TextUtils.isEmpty(address) && !TextUtils.isEmpty(province)) {
                        address = address.substring(province.length(), address.length());
                    }
                    if(getClass().getName().equals(MainActivity.class.getName())) {
                    Observable<Object> baseBeanObservable = RetrofitClient.getInstance().getHttpServices().uploadDrivermap(address, StringUtils.getPoint(aMapLocation.getLongitude(), aMapLocation.getLatitude()));
                    objectNetworkCallback.postRequest(baseBeanObservable, null);
                    }
                });
                locationHelp.initLocation();
        }
        }

    }


    /**
     * 登录失效弹框
     */
//    private void showSessionKeyNotFoundDialog(String type) {
//        SureDialog sureDialog = new SureDialog(this);
//        sureDialog.setTitleText(type)
//                .setPositiveListener(dialog -> {
//                    Hawk.deleteAll();
//                    toActivityClearTask(LoginActivity.class);
//                    dialog.dismiss();
//                });
//        sureDialog.show();
//    }
    protected void initView() {

    }

    protected void restoreSavedInstanceState(Bundle savedInstanceState) {

    }

    protected abstract @LayoutRes
    int getLayoutId();

    @Override
    protected void onResume() {
        super.onResume();

        for (BaseFragment fragment : fragments) {
            fragment.onFragmentVisibleChange(fragment.getUserVisibleHint());
        }
    }

    @Override
    protected void onDestroy() {
        ActivityManagerHelp.getInstance().remove(this);
        if (unbinder != null) {
            unbinder.unbind();
        }

        if (timeSubscribe != null && !timeSubscribe.isDisposed()) {
            timeSubscribe.dispose();
        }
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    /**
     * @return 是否登录
     */
    protected boolean isLogin() {
        String token = Hawk.get(HawkKeys.TOKEN_KEY);
        if (!TextUtils.isEmpty(token)) {
            return true;
        }
        return false;
    }

    /**
     * @param clz 跳转activity
     */
    public void startActivity(Class clz) {
        Intent intent = new Intent();
        intent.setClass(this, clz);
        startActivity(intent);
    }


    /**
     * @param
     */
    public void showLoadingDialog() {
        if (loadingDialog == null) {
            loadingDialog = new LoadingDialog(this);
        } else {
            loadingDialog.loadingAnimation();
        }
        if (!loadingDialog.isShowing()) {
            loadingDialog.show();
        }
    }

    /* *
     * 关闭加载框*/
    public void dismissDilog() {
        if (loadingDialog != null && loadingDialog.isShowing()) {
            loadingDialog.dismiss();
        }
    }


//    /**
//     * @return 是否有邮箱
//     */
//    public String userEmail() {
//        UserInfo userInfo = Hawk.get(HawkKeys.USERINFO_KEY);
//        if(userInfo != null) {
//            return userInfo.mail;
//        }
//        return "";
//    }
//
//    /**
//     * @return 获取username
//     */
//    public String getUserName() {
//        UserInfo userInfo = Hawk.get(HawkKeys.USERINFO_KEY);
//        if(userInfo != null) {
//            return userInfo.userName;
//        }
//        return "";
//    }

    /**
     * @param cls 清除task跳转
     */
    public void toActivityClearTask(Class cls) {
        Intent intent = new Intent(this, cls);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
        finish();
    }


    /**
     * 沉浸式状态栏
     */
    public void setStatusBarCol() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            try {
                Class decorViewClazz = Class.forName("com.android.internal.policy.DecorView");
                Field field = decorViewClazz.getDeclaredField("mSemiTransparentStatusBarColor");
                field.setAccessible(true);
                field.setInt(getWindow().getDecorView(), Color.TRANSPARENT);  //改为透明
            } catch (Exception e) {
            }
        }
    }


    /**
     * 显示加载框...
     */
//    public void showLoadingDialog() {
//        showLoadingDialog(-1);
//    }

    /**
     * @param loadingRes
     * 显示加载框
     */
//    public void showLoadingDialog(@StringRes int loadingRes) {
//        loadingDialog = new LoadingDialog(this);
//        if(loadingRes != -1) {
//            loadingDialog.setLoadingTxt(loadingRes);
//        }
//        if(!loadingDialog.isShowing()) {
//            loadingDialog.show();
//        }
//    }


    /**
     * 关闭加载框
     */
//    public void dismissDilog() {
//        if(loadingDialog != null && loadingDialog.isShowing()) {
//            loadingDialog.dismiss();
//        }
//    }

//    public void dialogLoading(Resource resource) {
//        dialogLoading(resource,-1);
//    }
//
//    public void dialogLoading(Resource resource,@StringRes int loadingRes) {
//        if(resource.status == Status.LOADING) {
//            showLoadingDialog(loadingRes);
//        } else {
//            dismissDilog();
//        }
//    }

//    /**
//     * @param frameLayout
//     * @param view
//     * @param drawable
//     * @param text
//     * 添加空页面
//     */
//    public void addEmptyView(FrameLayout frameLayout , View view, @DrawableRes int drawable , String text) {
//        frameLayout.removeView(view);
//        ImageView imageView = view.findViewById(R.id.emptyImg);
//        TextView textView = view.findViewById(R.id.emptyTv);
//
//        imageView.setImageResource(drawable);
//        textView.setText(text);
//
//        int paddingTop = getResources().getDimensionPixelSize(R.dimen.dp_150);
//        view.setPadding(0,paddingTop,0,0);
//        frameLayout.addView(view,-1);
//    }
    public int getStatusBarHeight() {
        int result = 0;
        int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }

}
